"""@mc.export 装饰器扩展

处理函数导出装饰器。
"""

from ..extension_base import extension_processor
from ..ir import IRContext, IRTemplate
from ..ir.declarations.function import IRFunctionNode


@extension_processor(
    "export_decorator",
    match_rule={"decorator": "mc.export", "node_type": "function"},
    priority=10,
)
def process_export_decorator(context: IRContext) -> None:
    """处理export装饰器"""
    node = context.node

    # 确保是函数节点
    if not isinstance(node, IRFunctionNode):
        return

    # 检查是否有export装饰器
    export_decorator = context.get_decorator("mc.export")
    if not export_decorator:
        # 也检查 "export" 装饰器
        export_decorator = context.get_decorator("export")
        if not export_decorator:
            return

    # 创建模板变量，包含节点信息和导出宏
    class NodeWrapper:
        def __init__(self, ir_node: IRFunctionNode):
            self.name = ir_node.name
            self.params = []
            self.return_type = ir_node.return_type
            self.export_macro = "MC_EXPORT"

    node_wrapper = NodeWrapper(node)
    template = IRTemplate(
        name=f"export_{node.name}",
        source_line=node.source_line,
        context={"node": node_wrapper},
    )
    template.set_extension_param(
        "template_content", "${node.export_macro} ${node.name}();"
    )

    # 将模板添加到模块的模板列表
    module = context.module
    templates = module.get_extension_param("templates", [])
    templates.append(template)
    module.set_extension_param("templates", templates)

    # 添加必要的头文件
    module.includes.add("<mc/export.h>")
